package com.tyc.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 测试手动提交offset
 */
public class CustomConsumerOffset {
    public static void main(String[] args) {
        //配置
        Properties properties = new Properties();
        properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092,127.0.0.1:9093");
        //反序列化
        properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //手动提交offset（默认自动）
        properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "false");
        //必须配置消费组ID
        properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        KafkaConsumer kafkaConsumer = new KafkaConsumer<String,String>(properties);
        //消费指定分区
        List<TopicPartition> topics = new ArrayList<>();
        TopicPartition p0 = new TopicPartition("test_g", 0);
        topics.add(p0);
        kafkaConsumer.assign(topics);
        while (true){
            // 间隔一秒拉一次
            ConsumerRecords consumerRecords = kafkaConsumer.poll(1000);
            for (Object consumerRecord : consumerRecords) {
                System.out.println(consumerRecord);
            }
            kafkaConsumer.commitSync();
            // 通常采用异步提交
//            kafkaConsumer.commitAsync();
        }
    }
}
